package com.gr.dmbackend.service.Impl.dormaddmin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.dmbackend.mapper.BuildingMapper;
import com.gr.dmbackend.mapper.DormitoryMapper;
import com.gr.dmbackend.mapper.StudentMapper;
import com.gr.dmbackend.model.Building;
import com.gr.dmbackend.model.Dormitory;
import com.gr.dmbackend.model.Student;
import com.gr.dmbackend.service.dormaddmin.UpdateStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UpdateStudentServiceImpl implements UpdateStudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public JSONObject updateStudent(Map<String, String> data) {

        JSONObject resp = new JSONObject();

        String studentId = data.get("studentId");
        String building = data.get("building");
        String dormId = data.get("dormId");
        String floor = "" + dormId.charAt(0);

        if (building.isEmpty()) {
            resp.put("error_message", "楼栋不能为空");
            return resp;
        }
        if (dormId.isEmpty()) {
            resp.put("error_message", "寝室号不能为空");
            return resp;
        }
        if (building.length() > 20) {
            resp.put("error_message", "楼栋长度超出限制");
            return resp;
        }
        if (dormId.length() > 10) {
            resp.put("error_message", "寝室号长度超出限制");
            return resp;
        }
        QueryWrapper<Building> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name", building);
        Building building1 = buildingMapper.selectOne(queryWrapper1);
        if (building1 == null) {
            resp.put("error_message", "当前楼栋不存在");
            return resp;
        }
        QueryWrapper<Dormitory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("dorm_id", dormId)
                .eq("building", building);
        Dormitory dormitory = dormitoryMapper.selectOne(queryWrapper2);
        if (dormitory == null) {
            resp.put("error_message", "当前寝室号不存在");
            return resp;
        }

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        Student student = studentMapper.selectOne(queryWrapper);
        if (student == null) {
            resp.put("error_message", "当前学生不存在");
            return resp;
        }

        student.setBuilding(building);
        student.setFloor(floor);
        student.setDormId(dormId);
        studentMapper.updateById(student);
        resp.put("error_message", "success");

        return resp;
    }
}
